import { combineResolvers } from 'graphql-resolvers'
import auth from '../../middlewares/auth'
import { wechat } from '../../config'

module.exports = {
  Query: {
    getLoginer: async (root, { code }, { user }) => {
      return user
    }
  },
  Mutation: {
    wxLogin: async (
      root,
      { code, appId },
      { services: { $wechat, $auth } }
    ) => {
      const user = await $wechat.wxLogin(code, appId)
      return $auth.sign(user)
    },
    wxUserInfo: combineResolvers(
      auth,
      async (
        root,
        { encryptedData, iv },
        { services: { $wechat, $user, $auth }, user }
      ) => {
        let userId = user.id
        let userInfo
        if (encryptedData) {
          userInfo = await $wechat.decryptInfo(encryptedData, iv, userId)
        }
        const updatedUser = await $user.updateWxUserInfo(userId, userInfo)
        return $auth.sign(updatedUser)
      }
    ),
    updateUserProfile: combineResolvers(
      auth,
      async (root, profile, { services: { $wechat, $user, $auth }, user }) => {
        const updatedUser = await $user.updateUserProfile(user.id, profile)
        return $auth.sign(updatedUser)
      }
    )
  }
}
